package com.fz.us.oa.web.controller.main.company;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.base.utils.EntityConfig;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Remind;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.TaskRecord;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.RemindService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.company.service.TaskRecordService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-09 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/taskRecord")
public class TaskRecordController extends BaseController {


    private static final long serialVersionUID = 3851349105893900794L;

    @Autowired
    private TaskRecordService taskRecordService;
    @Autowired
    private TaskEntityService taskEntityService;

    private static final EntityConfig entityConfig  = new EntityConfig();

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    JqGridPager pager,String type,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {

        Map<String,Object> params = new HashMap<String, Object>();
        params.put("state", BaseEnumManager.StateEnum.Enable);
        params.put("user", user);
        params.put("type", StringUtils.isNotEmpty(type)?Integer.parseInt(type):null);
        List<TaskRecord> taskRecordList = taskRecordService.getList(params);
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(TaskRecord taskRecord: taskRecordList){
            rMap = new HashMap<String, Object>();
            String bussinessId = taskRecord.getKeyId();
            String usernames = "";
            String pname = "";
            String url = "";
            String model = "";
            TaskEntity taskEntity = null;
            String key = "";
            if(StringUtils.isNotEmpty(bussinessId)){
                taskEntity = taskEntityService.getInfoByKeyId(bussinessId);
                pname = entityConfig.getValues(taskEntity.getEntityName());
                if(StringUtils.isNotEmpty(taskEntity.getEntityName())){

                    String rs =   taskEntity.getEntityName().substring( taskEntity.getEntityName().lastIndexOf(".")+1);
                    key = (new StringBuilder()).append(Character.toLowerCase(rs.charAt(0))).append(rs.substring(1)).toString();
                }
                url =  "../com/" + key + "/read?keyId=" +bussinessId  ;
                if(StringUtils.equals(type, "1")){
                    url +="&record=1";
                }else if(StringUtils.equals(type,"2")){
                    url +="&record=2";
                }
            }
            rMap.put("creater", taskEntity!=null?taskEntity.getCreater().getName():"");
            rMap.put("pname",pname);
            if(taskEntity != null && taskEntity.getEditors() != null){
                for(User user1 :taskEntity.getEditors()){
                    usernames += user1.getName()+",";
                }
            }
            if(StringUtils.isNotEmpty(usernames)){
                usernames = usernames.substring(0, usernames.length()-1);
            }
            rMap.put("usernames", usernames);
            rMap.put("id", taskRecord.getId());
            rMap.put("module",taskRecord.getModule());
            rMap.put("createTime", DataUtil.DateToString(taskRecord.getCreateTime(), "yyyy-MM-dd"));
            rMap.put("url",url);
            dataRows.add(rMap);
        }
        //不满10条，补充
        for(int i=0;i<10-taskRecordList.size();i++){
            rMap = new HashMap<String, Object>();
            rMap.put("pname", "");
            rMap.put("creater", "");
            rMap.put("usernames", "");
            rMap.put("module", "");
            rMap.put("id", "");
            rMap.put("createTime", "");
            rMap.put("url", "");
            dataRows.add(rMap);
        }
        data.put("page", 0);
        data.put("rows", 0);
        data.put("records", taskRecordList.size());
        data.put("total", 0);
        data.put("dataRows", dataRows);
        return data;
    }


    /**
     * 待办事宜
     */
    @RequestMapping(value = "toDoList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> toDoList(@CurrentUser User user,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        List<TaskEntity> taskEntityList = taskEntityService.getInfoByEditors(new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed}, user.getId());
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(TaskEntity taskEntity : taskEntityList){
            String entityName = "";
            String toUser = "";
            rMap = new HashMap<String, Object>();
            rMap.put("pname", entityConfig.getValues(taskEntity.getEntityName()));
            rMap.put("creater", taskEntity.getCreater().getName());
            if(taskEntity.getPrevUsers() != null){
                for(User users1:taskEntity.getPrevUsers()){
                    toUser += users1.getName()+",";
                }
            }
            if(StringUtils.isNotEmpty(toUser)){
                toUser = toUser.substring(0, toUser.length()-1);
            }
            rMap.put("toUser", toUser);
            rMap.put("time", DataUtil.DateToString(taskEntity.getCreateTime(), "yyyy-MM-dd HH:mm"));
            rMap.put("docId", taskEntity.getKeyId());
            if(StringUtils.isNotEmpty(taskEntity.getEntityName())){
                String rs =   taskEntity.getEntityName().substring( taskEntity.getEntityName().lastIndexOf(".")+1);
                entityName = (new StringBuilder()).append(Character.toLowerCase(rs.charAt(0))).append(rs.substring(1)).toString();
            }
            rMap.put("url", "../com/"+entityName+"/read?keyId=" + taskEntity.getKeyId() +"&todo=1");
            dataRows.add(rMap);
        }
        //不满10条，补充
        for(int i=0;i<10-taskEntityList.size();i++){
            rMap = new HashMap<String, Object>();
            rMap.put("pname", "");
            rMap.put("creater", "");
            rMap.put("toUser", "");
            rMap.put("time", "");
            rMap.put("docId", "");
            rMap.put("url", "");
            dataRows.add(rMap);
        }
        data.put("page", 0);
        data.put("rows", 0);
        data.put("records", taskEntityList.size());
        data.put("total", 0);
        data.put("dataRows", dataRows);
        return data;
    }

    /**
     * 草稿
     */
    @RequestMapping(value = "draftList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> draftList(@CurrentUser User user,
                                        JqGridPager pager,
                                        @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        List<TaskEntity> taskEntityList = taskEntityService.getInfoByDraft(FlowEnum.ProcessState.Draft, user);
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(TaskEntity taskEntity : taskEntityList){
            String entityName = "";
            String toUser = "";
            rMap = new HashMap<String, Object>();
            rMap.put("pname", entityConfig.getValues(taskEntity.getEntityName()));
            rMap.put("creater", taskEntity.getCreater().getName());
            if(taskEntity.getPrevUsers() != null){
                for(User users1:taskEntity.getPrevUsers()){
                    toUser += users1.getName()+",";
                }
            }
            if(StringUtils.isNotEmpty(toUser)){
                toUser = toUser.substring(0, toUser.length()-1);
            }
            rMap.put("toUser", toUser);
            rMap.put("time", DataUtil.DateToString(taskEntity.getCreateTime(), "yyyy-MM-dd HH:mm"));
            rMap.put("docId", taskEntity.getKeyId());
            if(StringUtils.isNotEmpty(taskEntity.getEntityName())){
                String rs =   taskEntity.getEntityName().substring( taskEntity.getEntityName().lastIndexOf(".")+1);
                entityName = (new StringBuilder()).append(Character.toLowerCase(rs.charAt(0))).append(rs.substring(1)).toString();
            }
            rMap.put("url", "../com/"+entityName+"/read?keyId=" + taskEntity.getKeyId() +"&draft=1");
            dataRows.add(rMap);
        }
        //不满10条，补充
        for(int i=0;i<10-taskEntityList.size();i++){
            rMap = new HashMap<String, Object>();
            rMap.put("pname", "");
            rMap.put("creater", "");
            rMap.put("toUser", "");
            rMap.put("time", "");
            rMap.put("docId", "");
            rMap.put("url", "");
            dataRows.add(rMap);
        }
        data.put("page", 0);
        data.put("rows", 0);
        data.put("records", taskEntityList.size());
        data.put("total", 0);
        data.put("dataRows", dataRows);
        return data;
    }

}
